package com.lbs.jiepiaisi.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ImageView;

import com.google.gson.Gson;
import com.lbs.jiepiaisi.R;
import com.lbs.jiepiaisi.base.ErrorException;
import com.lbs.jiepiaisi.base.ProgressObserver;
import com.lbs.jiepiaisi.base.ResultException;
import com.lbs.jiepiaisi.bean.EqnoLoginBean;
import com.lbs.jiepiaisi.bean.PhotoImgBean;
import com.lbs.jiepiaisi.config.Api;
import com.lbs.jiepiaisi.fragment.PhotoFragment;
import com.lbs.jiepiaisi.utils.LocationPerUtil;
import com.lbs.jiepiaisi.utils.PhotoPerUtil;
import com.lbs.jiepiaisi.utils.RxSchedulers;
import com.lbs.jiepiaisi.utils.ToastUtil;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
import cn.bingoogolapple.qrcode.core.CameraPreview;
import cn.bingoogolapple.qrcode.core.QRCodeView;
import cn.bingoogolapple.qrcode.zxing.ZXingView;
import io.reactivex.observers.DisposableObserver;

/**
 * 时间：2017/6/21 14:42
 * 作用：扫描条形码或者二维码类
 */
public final class CommonScanActivity extends AppCompatActivity implements QRCodeView.Delegate {

    private static final String TAG = CommonScanActivity.class.getSimpleName();

    //@Bind(R.id.zxing_view)
    private ZXingView mZXingView;

    //@Bind(R.id.iv_light)
    private ImageView bulbSwitch;

    //@Bind(R.id.go_back)
    private ImageView goBack;

    private EqnoLoginBean mEqnoLoginBean;
    private PhotoImgBean mPhotoImgBean;

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.activity_scan_qrcode);
        //ButterKnife.bind(this);
        initView();

    }

    void initView() {
        mZXingView = findViewById(R.id.zxing_view);
        mZXingView.setDelegate(this);
        bulbSwitch = findViewById(R.id.iv_light);
        goBack = findViewById(R.id.go_back);

        // 闪光灯开关
        bulbSwitch.setOnClickListener(v -> {
            v.setSelected(!v.isSelected());
            if (v.isSelected()) {
                mZXingView.openFlashlight();
            } else {
                mZXingView.closeFlashlight();
            }
        });
        goBack.setOnClickListener(v -> this.finish());
    }

    @Override
    protected void onStart() {
        super.onStart();
        mZXingView.startCamera(); // 打开后置摄像头开始预览，但是并未开始识别

        mZXingView.startSpotAndShowRect(); // 显示扫描框，并开始识别
    }

    @Override
    protected void onStop() {
        mZXingView.stopCamera(); // 关闭摄像头预览，并且隐藏扫描框
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        mZXingView.onDestroy(); // 销毁二维码扫描控件
        super.onDestroy();
    }

    private void vibrate() {
        Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        vibrator.vibrate(200);
    }

    public void loginByScan(String eqNo) {
        if (!LocationPerUtil.checkLocationPermission(this)) {
            ToastUtil.show("请打开定位权限");
            return;
        }

        if (!PhotoPerUtil.checkCameraPermission(this)) {
            ToastUtil.show("请打开相机权限");
            return;
        }

        /** 设备号登录*/
        Api.getInstance().createService().eqnoLogin(eqNo)
                .compose(RxSchedulers.observableIO2Main(this))
                .subscribe(new ProgressObserver<EqnoLoginBean>(this,true) {
                    @Override
                    public void onSuccess(EqnoLoginBean result) {
                        // code = 0
                        // 检查图片数量
                        mEqnoLoginBean = result;
                        loadPhotoInfo();
                    }

                    @Override
                    public void onFailure(ErrorException e) {
                        // code = 1,2,3...
                        Log.e("CommonScanActivity",e.getCode()+"");
                        switch (e.getCode()){
                            case 1:
                                ToastUtil.show("信息已提交，正在审核！");
                                startSpot();
                                break;
                            case 2:
                                ToastUtil.show("该设备号不存在！");
                                startSpot();
                                break;
                            case 3:
                                ToastUtil.show("信息不全,请在平台完善信息!");
                                startSpot();
                                break;
                            default:
                                ToastUtil.show(e.getMsg());
                                startSpot();
                                break;
                        }
                    }
                });
    }

    public void loadPhotoInfo() {
        Api.getInstance().createService()
                .loadImg(mEqnoLoginBean.getResult().getEqId())
                .compose(RxSchedulers.observableIO2Main(this))
                .subscribe(new DisposableObserver<Object>() {

                    @Override
                    protected void onStart() {
                        super.onStart();
                    }

                    @Override
                    public void onNext(Object o) {
                        // 补拍上传
                        PhotoImgBean photoImgBean = new PhotoImgBean();
                        PhotoImgBean.InstallInfo installInfo = new PhotoImgBean.InstallInfo();
                        List<PhotoImgBean.FileInfo> files = new ArrayList<>();
                        try {
                            String json = new Gson().toJson(o);
                            Log.e("CommonScanActivity",json);
                            JSONArray result = new JSONObject(json).getJSONArray("result");

                            JSONObject info = result.getJSONObject(0);
                            if (info.length() == 0) {
                                installInfo.setInstaller("");
                                installInfo.setInstallerPhone("");
                                installInfo.setInstallerPosition("");
                            } else {
                                installInfo.setInstaller(info.getString("installer"));
                                installInfo.setInstallerPhone(info.getString("installerPhone"));
                                installInfo.setInstallerPosition(info.getString("installerPosition"));
                            }

                            JSONArray list = result.getJSONArray(1);

                            for (int i = 0; i < list.length(); i++) {
                                JSONObject fileInfoModel = list.getJSONObject(i);
                                PhotoImgBean.FileInfo fileInfo = new PhotoImgBean.FileInfo();
                                fileInfo.setType(fileInfoModel.getInt("type"));
                                files.add(fileInfo);
                            }

                            photoImgBean.setInstallInfo(installInfo);
                            photoImgBean.setFiles(files);

                            mPhotoImgBean = photoImgBean;

                            if (files.size() >= 3) {
                                Log.e("CommonScanActivity","审核中了");
                                ToastUtil.show("信息已提交，正在审核！");
                                startSpot();
                                return;
                            }

                            ToastUtil.show("登录成功");
                            Intent photoActivity = new Intent(CommonScanActivity.this, PhotoActivity.class);
                            Bundle bundle = new Bundle();
                            bundle.putSerializable("eqnoLoginBean", mEqnoLoginBean);
                            bundle.putSerializable("photoImgBean", photoImgBean);
                            bundle.putSerializable("uploadImgType", PhotoFragment.UploadImgType.UploadImgTypeSupplement);
                            photoActivity.putExtras(bundle);
                            startActivity(photoActivity);

                            Log.e("CommonScanActivity","补拍上传");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        if (e instanceof ResultException) {
                            ResultException ex = (ResultException)e;
                            if (ex.getCode() == 1) {
                                Log.e("CommonScanActivity","完整上传");
                                // 完整上传
                                ToastUtil.show("登录成功");
                                Intent photoActivity = new Intent(CommonScanActivity.this, PhotoActivity.class);
                                Bundle bundle = new Bundle();
                                bundle.putSerializable("eqnoLoginBean", mEqnoLoginBean);
//                                bundle.putSerializable("photoImgBean", mPhotoImgBean);
                                bundle.putSerializable("uploadImgType", PhotoFragment.UploadImgType.UploadImgTypeNormal);
                                photoActivity.putExtras(bundle);
                                startActivity(photoActivity);
                            }
                        }
                    }

                    @Override
                    public void onComplete() {
                        Log.e("66666","onComplete");
                    }
                });
    }

    @Override
    public void onScanQRCodeSuccess(String result) {
        Log.e("CommonScanActivity", "666result:" + result);
        vibrate();// 振动
        loginByScan(result);
        //mZXingView.startSpot(); // 开始识别
        //new Handler().postDelayed(() -> mZXingView.startSpot(), 1800);

    }

    public void startSpot(){
        new Handler().postDelayed(() -> mZXingView.startSpot(), 1800);
    }

    @Override
    public void onCameraAmbientBrightnessChanged(boolean isDark) {
        // 这里是通过修改提示文案来展示环境是否过暗的状态，接入方也可以根据 isDark 的值来实现其他交互效果
        String tipText = mZXingView.getScanBoxView().getTipText();
        String ambientBrightnessTip = "\n环境过暗，请打开闪光灯";
        if (isDark) {
            if (!tipText.contains(ambientBrightnessTip)) {
                mZXingView.getScanBoxView().setTipText(tipText + ambientBrightnessTip);
            }
        } else {
            if (tipText.contains(ambientBrightnessTip)) {
                tipText = tipText.substring(0, tipText.indexOf(ambientBrightnessTip));
                mZXingView.getScanBoxView().setTipText(tipText);
            }
        }
    }

    @Override
    public void onScanQRCodeOpenCameraError() {
        Log.e("CommonScanActivity","扫描出错了");
    }
}